import { Button, Card, Form, Input, message, Space, Table, Modal } from 'antd'
import { SearchOutlined, EditOutlined, DeleteOutlined, ExclamationCircleFilled } from '@ant-design/icons'

import React, { useEffect, useState } from 'react'
import { ColumnsType } from 'antd/lib/table'
import { deleteById, getHospitalSetList, removeBatch } from '@/api/hospital/hospitalSet'
import { IHospitalSetItem, IHospitalSetList } from '@/api/hospital/model/hospitalSetTypes'
import { useNavigate } from 'react-router-dom'
const { confirm } = Modal;
export default function HospitalSet() {
    const navigate = useNavigate();
    // 1. 创建form对象
    const [form] = Form.useForm();
    const onFinish = () => {
        // 重新设置 hosname 和 hoscode的状态值即可
        // console.log(form.getFieldsValue());
        // 获取表单数据，注意 必须要有name属性 hosname  hoscode
        let { hosname, hoscode } = form.getFieldsValue();
        // 设置状态
        setHoscode(hoscode);
        setHosname(hosname);
        // 重置页码为第一页
        page !== 1 && setPage(1)
    }
    // 清空操作
    const clear = () => {
        // 1. 重置表单的显示
        form.resetFields();
        // 2. 重置状态数据 hosname 和 hoscode 的值为undefined
        setHoscode(undefined);
        setHosname(undefined);
        // 重置页码
        setPage(1);
    }

    const deleteHospital = (id: string | number) => {
        confirm({
            title: '确定删除么?',
            icon: <ExclamationCircleFilled />,
            content: '删除医院设置',
            async onOk() {
                // 发送请求删除数据
                await deleteById(id);
                message.success('删除成功');
                // 刷新列表
                _getHospitalSetList();
            }
        });

    }

    const columns: ColumnsType<IHospitalSetItem> = [
        {
            title: '序号',
            width: 60,
            align: 'center',
            render(value: any, row: any, index: number) {
                return (page - 1) * pageSize + (index + 1)
            }
        },
        {
            title: '医院名称',
            dataIndex: 'hosname'
        },
        {
            title: '医院编号',
            dataIndex: 'hoscode'
        },
        {
            title: 'api基础路径',
            dataIndex: 'apiUrl'
        },
        {
            title: '签名',
            width: 120,
            dataIndex: 'signKey'
        },
        {
            title: '联系人姓名',
            dataIndex: 'contactsName'
        },
        {
            title: '联系人手机',
            dataIndex: 'contactsPhone'
        },
        {
            title: '操作',
            fixed: 'right',
            width: 100,
            render(row: IHospitalSetItem) {
                return (
                    <Space>
                        <Button type='primary' icon={<EditOutlined />} onClick={() => navigate('/syt/hospital/hospitalSet/edit/' + row.id)}></Button>
                        <Button type='primary' icon={<DeleteOutlined />} danger onClick={() => deleteHospital(row.id)}></Button>
                    </Space>
                )
            }
        }
    ]
    // 定义相关状态数据
    let [page, setPage] = useState<number>(1); // 当前页
    let [pageSize, setPageSize] = useState<number>(3);// 每页几条
    let [total, setTotal] = useState<number>(10);// 总条数
    let [hospitalSetList, setHospitalSetList] = useState<IHospitalSetList>([]);//医院设置列表数据
    let [hosname, setHosname] = useState<string>();// 医院名称
    let [hoscode, setHoscode] = useState<string>();// 医院编号
    // 设置被选中项目的ids数组
    let [ids, setIds] = useState<React.Key[]>([])
    // loading控制
    let [loading, setLoading] = useState<boolean>(false)

    // 获取医院设置列表数据
    const _getHospitalSetList = async () => {
        setLoading(true);
        let { records, total } = await getHospitalSetList({ page, limit: pageSize, hoscode, hosname })
        // 设置状态
        setHospitalSetList(records);
        setTotal(total);
        setLoading(false);
        // console.log('records: ', records);
        // console.log('total: ', total);
    }
    /**
     * 批量删除
     */
    const _removeBatch =  () => {
        //1 弹出模态框
        //2. 发送ajax请求
        //3. 提示删除成功
        //4. 刷新列表
        //5. 设置ids状态为空数组
        confirm({
            title: '确定批量删除么?',
            icon: <ExclamationCircleFilled />,
            content: '批量删除医院设置',
            async onOk() {
                await removeBatch(ids);
                message.success('批量删除成功');
                // 刷新列表
                _getHospitalSetList();
                // 设置ids状态为空数组
                setIds([])
            }
        });
    }
    // 组件加载完后执行
    useEffect(() => {
        _getHospitalSetList();
    }, [page, pageSize, hosname, hoscode])
    return (
        <Card>
            {/* 1. from  */}
            <Form
                // 2. form绑定表单
                form={form}
                layout='inline'
                name="basic"
                onFinish={onFinish}
            >
                <Form.Item
                    name="hosname"
                >
                    <Input placeholder='医院名称' />
                </Form.Item>

                <Form.Item
                    name="hoscode"
                >
                    <Input placeholder='医院编号' />
                </Form.Item>

                <Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                            查询
                        </Button>
                        <Button onClick={clear} disabled={!hoscode && !hosname}>
                            清空
                        </Button>
                    </Space>
                </Form.Item>
            </Form>
            {/* 2. buttons */}
            <Space className="mt">
                <Button type="primary" onClick={() => navigate('/syt/hospital/hospitalSet/add')}>添加</Button>
                <Button disabled={!ids.length} onClick={_removeBatch}>批量删除</Button>
            </Space>
            {/* 3. table表格 */}

            <Table
                rowKey={'id'}
                loading={loading}
                // 表格添加复选框行可选项
                rowSelection={{
                    // 有被选中改变的时候，触发的函数，参数是被选中的 rowKey指定的数组
                    onChange(selectedKeys: React.Key[]) {
                        // console.log('selectedKeys',selectedKeys);
                        setIds(selectedKeys);
                    }
                }}
                className="mt"
                columns={columns}
                dataSource={hospitalSetList}
                pagination={{
                    current: page,
                    pageSize,
                    total,
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: [5, 10, 20],
                    // 点击分页按钮完成分页
                    onChange(page: number, pageSize) {
                        setPage(page);
                        setPageSize(pageSize);
                    }
                }}
                scroll={{
                    x: 1300
                }}
            />
        </Card>
    )
}
